<template>
    <div class="body">
        <div style="font-size: 30px">状态：{{ state }}</div>
        <div  style="font-size: 24px;margin: 0 auto">
            <el-link type="primary" href="https://gitee.com/LLLLLLin/openharmony_commit" style="margin-right: 10px" slot="reference">代码仓库地址</el-link>
            <el-link type="primary" href="https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoStargazers?ex=no" style="margin-right: 10px" slot="reference">gitee文档</el-link>

        </div>
        <div class="flex-between" style="font-size: 24px">
            配置
        </div>
        <div class="flex-between">
            <el-popover
                placement="top-start"
                title="token获取"
                width="200"
                trigger="hover"
                content="访问https://gitee.com/api/v5/swagger#/getV5OrgsOrgRepos 后,点击右上角申请授权，授权后access_token一栏即可看到">
                <el-link type="primary" style="margin-right: 10px" slot="reference">token:</el-link>
            </el-popover>

            <el-input v-model="token" placeholder="请输入token" style="width: 200px;flex-grow: 1"></el-input>
        </div>
        <div class="flex-between">
            <div>请选择org组织（多选，右侧可新增组织）:</div>
            <el-input placeholder="新增组织" v-model="orgInput" style="width: 200px">
                <el-button slot="append" icon="el-icon-plus" @click="addOrg"></el-button>
            </el-input>
        </div>
        <div class="flex-between">
            <el-checkbox-group v-model="selectedOrg">
                <el-checkbox-button v-for="org in orgOptions" :label="org" :key="org">{{ org }}</el-checkbox-button>
            </el-checkbox-group>
            <el-button type="warning" style="margin-left: 10px" @click="clearOrg">重置</el-button>
        </div>
        <el-divider></el-divider>
        <div class="flex-between" style="font-size: 24px">
            操作
        </div>
        <div class="flex-row">
            <el-button type="primary" @click="getRepo" :disabled="isLoadingRepo"> 1.根据组织获取仓库: {{ repos.length }}</el-button>
            <el-button type="primary" @click="getPR" :disabled="isLoadingRepo"> 1.获取PR数据: {{ exportData.length }}</el-button>
        </div>
        <div class="flex-row">
            <el-button type="success" icon="el-icon-download"  @click="exportExcel">导出EXCEL</el-button>
        </div>
    </div>
</template>

<script>

import export_json_to_excel from "../excel/Export2Excel";

import FileSaver from 'file-saver';
import * as XLSX from 'xlsx'

export default {
    name: 'OHAndSig',
    data() {
        return {
            token: '',
            selectedOrg: ['openharmony', 'OpenHarmony-SIG', 'OpenHarmony-TPC'],
            orgOptions: ['openharmony', 'OpenHarmony-SIG', 'OpenHarmony-TPC'],
            orgInput: '',
            repos: [],
            exportData: [],
            isLoadingRepo: false,
            isLoadingCommit: false,
            state: '等待中',
            isLoadingStat: false,
            fields: {
                org: 'org',
                repo: 'repo',
                commit_url: 'commitUrl',
                html_url: 'htmlUrl',
                author_name: 'authorName',
                author_email: 'authorEmail',
                author_date: 'authorDate',
                committer_name: 'committerName',
                committer_email: 'committerEmail',
                committer_date: 'committerDate',
                committer_message: 'committerMessage',
                additions: 'additions',
                deletions: 'deletions',
                total: 'total',
            }
        }
    },
    mounted() {
        this.initAxios()
    },
    methods: {
        initAxios() {
            this.axios.interceptors.response.use(
                response => {
                    // 如果返回的状态码为200，说明接口请求成功，可以正常拿到数据
                    // 否则的话抛出错误
                    if (response && response.status === 200) {
                        return Promise.resolve(response);
                    } else {
                        return Promise.reject(response);
                    }
                },

                error => {
                    let msg = ''
                    if (error &&error.status && error.response.status) {
                        msg = error.response.status
                    }
                    this.$message.error('请求出错，点击F12进入控制台查看详情：' + msg)
                    console.error(error)
                }
            );
        },
        addOrg() {
            this.orgOptions.push(this.orgInput)
        },
        clearOrg() {
            this.orgOptions = ['openharmony', 'OpenHarmony-SIG', 'OpenHarmony-TPC']
        },
        async getRepo() {
            try {
                this.isLoadingRepo = true
                this.repos = []
                for (let i = 0; i < this.selectedOrg.length; i++) {
                    let org = this.selectedOrg[i]
                    await this.getRepoByOrg(org)
                }
                this.state = 'repo 获取完毕'
            } catch (e) {
                this.state = 'repo 获取失败 F12控制台查看错误'
                console.error(e)
            } finally {
                this.isLoadingRepo = false
            }
        },
        async getRepoByOrg(org) {
            // 获取openharmony下public仓库中
            this.state = '获取openharmony下public仓库中'
            let page = 0
            let totalPage = 0
            const count = 100
            try {
                do {
                    page++
                    let response = await this.axios.get(`https://gitee.com/api/v5/orgs/${org}/repos?access_token=${this.token}&type=public&page=${page}&per_page=${count}`)
                    if (!totalPage) {
                        totalPage = response.headers.total_page
                    }
                    response.data.forEach(item => {
                        this.repos.push({org: org, repo: item.path,url: item.html_url,update:item.updated_at,create:item.created_at})
                    })

                } while (page < totalPage)
            } catch (e) {
                this.$message.error('获取仓库失败F12控制台查看详情')
                console.error('获取仓库失败')
                console.error(e)
            }
            console.log(`获取${org}所有public仓库完毕`)
            console.log('repos：')
            console.log(this.repos)

        },
        getPR(){
            this.exportData = []
            this.repos.forEach(item=>{
                this.getPRData(item.org,item.repo,item)
            })
        },
        getPRData(owner,repo,item) {
            this.axios.get(`https://gitee.com/api/v5/repos/${owner}/${repo}/pulls?access_token=${this.token}&state=all&sort=created&direction=desc&page=1&per_page=20`)
                .then(async response1 => {
                    if (!response1 || !response1.data) {
                        console.warn(response1)
                        return
                    }
                    if (response1.data && response1.data.length > 0){
                        item.prUrl = response1.data[0].html_url
                        item.prCreateDate = response1.data[0].created_at
                        item.prUpdateDate = response1.data[0].updated_at
                    }
                    this.exportData.push(item)
                })
        },
        //导出的方法
        exportExcel() {
            const tHeader = ["org" , "repo" , "url" , "update" , "create" ,"prUrl","prCreateDate","prUpdateDate"]
            // 上面设置Excel的表格第一行的标题
            // const filterVal = ["operationName", "operationType", "operationDate",'operationMsg'];
            const filterVal = ["org" , "repo" , "url" , "update" , "create" ,"prUrl","prCreateDate","prUpdateDate"]
            // 上面的index、nickName、name是tableData里对象的属性
            const list = this.exportData; //把data里的tableData存到list
            const data = this.formatJson(filterVal, list);
            const name = '所有repo数据'
            export_json_to_excel(tHeader, data, name);
        },

        formatJson(filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => v[j]));
        }
    }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
    font-weight: normal;
}

ul {
    list-style-type: none;
    padding: 0;
}

li {
    display: inline-block;
    margin: 0 10px;
}

a {
    color: #42b983;
}

.flex-row {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin: 10px 0;
    /*flex-wrap: wrap;*/
}

.flex-between {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    margin: 10px 0;
}

.body {
    width: 900px;
    margin: 0 auto;
}
</style>
